package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录拦截
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //解决跨域拦截与静态请求拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //1.识别请求映射方法头顶是否贴@RequireLogin
        String token = request.getHeader("token");
        //所有访问如果有登陆，都重置30分钟
        UserInfo user = userInfoRedisService.getUserByToken(token);

        HandlerMethod hm = (HandlerMethod) handler;
        if (hm.hasMethodAnnotation(RequireLogin.class)) {
            //2.如果贴了需要校验
            if (user == null) {
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));

                return false;
            }
            return true;
        }
        //2

        //3

        //获取token
//        String token = request.getHeader("token");
//
//        UserInfo user = userInfoRedisService.getUserByToken(token);
//
//        if (user == null) {
//            response.setContentType("application/json;charset=utf-8");
//            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
//
//            return false;
//        }
//
//        return true;
        return true;
    }
}
